package tianhao.luo.stack;

/**
 * @author: tianhao.luo@hand-china.com 2021/3/7  22:42
 */
public class ArrayStack<E> {

    /**
     * 数据存放
     */
    public Object[] data = null;

    /**
     * 栈的容量
     */
    public int maxSize = 0;

    /**
     * 栈顶指针
     */
    public int top = -1;


    public ArrayStack() {
        this(10);
    }

    public ArrayStack(int initialSize) {
        if (initialSize > 0) {
            this.maxSize = initialSize;
            data = new Object[initialSize];
        } else {
            throw new RuntimeException("initialSize(" + initialSize + ") is less than or equal to zero!");
        }
    }

    /**
     * 入栈
     *
     * @param e 元素
     * @return 入栈成功true
     */
    public boolean push(E e) {
        // 栈顶指针为于栈的最大长度处，无法继续入栈了
        if (isFull()) {
            throw new RuntimeException("this stack is completed!");
        } else {
            data[++top] = e;
            return true;
        }
    }


    /**
     * 出栈
     *
     * @return 栈顶元素
     */
    public E pop() {
        if (isEmpty()) {
            throw new RuntimeException("this stack is empty!");
        } else {
            return (E) data[top--];
        }
    }


    /**
     * 查询栈顶元素
     *
     * @return 返回栈顶元素
     */
    public E peek() {
        if (isEmpty()) {
            throw new RuntimeException("this stack is empty!");
        } else {
            return (E) data[top];
        }
    }

    public int getSize() {
        return top+1;
    }


    public boolean isFull() {
        return top == this.maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 展示时,从栈顶开始
     */
    public void list(){
        if(isEmpty()){
            throw new RuntimeException("this stack is empty!");
        }
        for (int i = top; i >=0; i--) {
            System.out.println("索引:"+i+",元素为:"+data[i]);
        }
    }
}
